package com.suxin.thread.schedulev2;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Tang
 * @classname JobExecutorContext
 * @description [ 任务流执行上下文 ]
 * @date 2021/6/10 13:24
 */
public class JobExecutorContext {

    /**
     * 每个任务流 维护一个线程池
     */
    private static ConcurrentHashMap<Integer, ThreadPoolExecutor> taskExecutorThreadPoolRepository =
            new ConcurrentHashMap<>(16);

    public static void registerTaskExecutorThreadPool(int jobId, ThreadPoolExecutor poolExecutor) {
        taskExecutorThreadPoolRepository.put(jobId, poolExecutor);
    }

    public static ThreadPoolExecutor getCurrentTaskExecutorThreadPool(int jobId) {
        return taskExecutorThreadPoolRepository.get(jobId);
    }

    public static void removeTaskExecutorThreadPool(int jobId) {
        taskExecutorThreadPoolRepository.remove(jobId);
    }

    public static void sleepIfIdle(ThreadPoolExecutor poolExecutor) {
        if (poolExecutor.getQueue().size() == 0) {
            int sleepTime = poolExecutor.getMaximumPoolSize() - poolExecutor.getActiveCount() + 1;
            try {
                TimeUnit.SECONDS.sleep(sleepTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


}